package socket.tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 基于TCP协议的socket通信，实现用户登录
 * 服务端
 * 测试，先启动服务端，后启动客户端
 */
public class Server {
    public static void main(String[] args) {
        try {
            //1、创建一个服务器socket，即ServerSocket，指定绑定端口，并监听此端口
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("****服务器已经启动，等待客户端连接****");
            //2、调用accept()方法开始监听，等待客户端连接，阻塞
            Socket socket = serverSocket.accept();
            //3、获取输入字节流
            InputStream is = socket.getInputStream();
            //4、获取字符流
            InputStreamReader isr = new InputStreamReader(is);
            //5、封装成缓冲流
            BufferedReader bf = new BufferedReader(isr);
            String data = null;
            while ((data = bf.readLine()) != null) {
                System.out.println("我是服务器，客户端：" + data);
            }
            //关闭输入流
            socket.shutdownInput();
            //打开输出字节流，向客户端输出响应信息
            OutputStream os = socket.getOutputStream();
            //包装成打印流
            PrintWriter ps = new PrintWriter(os);
            ps.write("欢迎您！");
            ps.flush();
            ps.close();
            os.close();
            //关闭资源
            bf.close();
            isr.close();
            is.close();
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
